<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router'
import userApi from '../api/User_api.js'
import loginApi from '../api/Login_api.js'
import { ElMessage } from 'element-plus'

const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const router = useRouter();
const userInfo = ref({
  id:0
});

// 获取当前用户信息
const getUserInfo = async () => {
  try {
    const res = await loginApi.loginInfo();
    userInfo.value = res;
  } catch (error) {
    console.error('获取用户信息失败', error);
    ElMessage.error('获取用户信息失败');
  }
}

// 表单验证规则
const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

const onSubmit = async () => {
  try {
    // 验证原密码是否正确（这里需要调用API验证）
    // 假设有一个验证密码的API
    // const isValid = await userApi.validatePassword(userInfo.value.id, form.value.oldPassword);

    // 如果没有验证API，可以先获取用户信息再比较
    if (form.value.oldPassword!=='' && form.value.oldPassword!=null) {
      if(!userApi.validatePassword(userInfo.value.id,form.value.oldPassword)){
        ElMessage.error('原密码不正确');
      }
    }

    // 更新密码
    await userApi.edit({
      ...userInfo.value,
      userPassword: form.value.newPassword
    });

    ElMessage.success('密码修改成功');
    router.push('/Myself');
  } catch (error) {
    console.error('修改密码失败', error);
    ElMessage.error('修改密码失败');
  }
}

// 初始化获取用户信息
getUserInfo();
</script>

<template>
  <div class="change-password-container">
    <h2>修改密码</h2>
    <el-form :model="form" :rules="rules" label-width="100px" style="max-width: 500px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="router.push('/Myself')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.change-password-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #409EFF;
}
</style>